﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using PairingMatrix.ViewModel;
using System.Linq;

namespace PairingMatrix.View.Behavior
{
    public class ArrangePairBehavior : Behavior<Grid>
    {
        private PairedWithViewModel _pairedWithViewModel;

        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
            {
                _pairedWithViewModel = (PairedWithViewModel)AssociatedObject.DataContext;
                _pairedWithViewModel.PropertyChanged += PairedWithViewModel_PropertyChanged;
                SetPosition();
            };
        }

        void PairedWithViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Position")
            {
                SetPosition();
            }
        }

        private void SetPosition()
        {
            var parent = (ContentPresenter) VisualTreeHelper.GetParent(AssociatedObject);

            Canvas.SetTop(parent, _pairedWithViewModel.Position.Y);
            Canvas.SetLeft(parent, _pairedWithViewModel.Position.X);
        }
    }
}
